import { Injectable } from '@nestjs/common';
import * as puppeteer from 'puppeteer';
import { ICrawler, NovelInfo, ChapterInfo, ChapterContent } from './interfaces/crawler.interface';

@Injectable()
export class FanqieCrawler implements ICrawler {
  private browser: puppeteer.Browser;

  async initBrowser() {
    if (!this.browser) {
      const executablePath = process.env.CHROME_EXECUTABLE_PATH ||
        'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';

      this.browser = await puppeteer.launch({
        headless: 'new',
        executablePath,
        args: ['--no-sandbox', '--disable-setuid-sandbox'],
      });
    }
  }

  getSource(): string {
    return 'fanqie';
  }

  validateUrl(url: string): boolean {
    return url.includes('fanqienovel.com') ||
           url.includes('novel.toutiao.com') ||
           url.includes('changdunovel.com');
  }

  async getNovelInfo(url: string): Promise<NovelInfo> {
    await this.initBrowser();
    const page = await this.browser.newPage();

    try {
      await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
      await page.goto(url, { waitUntil: 'networkidle2' });

      // 等待页面加载完成
      await page.waitForTimeout(3000);

      // 尝试点击"更多"按钮以展开完整的小说简介
      try {
        const moreButtonExists = await page.evaluate(() => {
          return !!document.querySelector('.precise-ellipsis-more-button');
        });

        if (moreButtonExists) {
          await page.click('.precise-ellipsis-more-button');
          // 等待内容展开
          await page.waitForTimeout(2000);
          console.log('✅ 已点击"更多"按钮，展开完整小说简介');
        }
      } catch (error) {
        console.log('⚠️ 未找到"更多"按钮或点击失败，继续获取基本信息');
      }

      const novelInfo = await page.evaluate(() => {
        // 根据实际页面结构获取小说信息
        let title = '';
        let author = '';
        let cover = '';
        let description = '';
        let category = '';
        let wordCount = '';
        let status = 0;

        // 获取页面主要信息容器
        const mainContainer = document.querySelector('.wrapper') || document.body;

        // 获取书名 - 优先使用book-info-name类
        const titleElement = document.querySelector('.book-info-name') ||
                            document.querySelector('.book-info-name.less-margin') ||
                            document.querySelector('h1');
        title = titleElement?.textContent?.trim() || '';

        // 获取分类、状态、字数 - 分别在不同元素中
        const detailElements = mainContainer.querySelectorAll('.book-info-detail div, .book-info-detail *');
        let categoryFound = false;
        let statusFound = false;
        let wordCountFound = false;

        detailElements.forEach((element) => {
            const text = element.textContent?.trim();
            if (!text) return;

            // 分类 (如: 玄幻脑洞)
            if (!categoryFound && !text.includes('完结') && !text.includes('万字') && text.length < 10) {
                category = text;
                categoryFound = true;
            }
            // 状态 (如: 完结)
            else if (!statusFound && text.includes('完结')) {
                status = 1;
                statusFound = true;
            }
            // 字数 (如: 100.1万字)
            else if (!wordCountFound && text.includes('万字')) {
                wordCount = text;
                wordCountFound = true;
            }
        });

        // 获取简介 - 优先从.fq-masking.all-border-box获取（点击"更多"按钮后出现）
        const detailContainer = document.querySelector('.fq-masking.all-border-box');
        if (detailContainer) {
            const text = detailContainer.textContent?.trim();
            if (text && text.length > 50) {
                description = text;
            }
        }

        // 如果没有找到详情容器，使用原来的逻辑作为备用
        if (!description) {
            const descElements = document.querySelectorAll('div');
            for (const element of descElements) {
                const text = element.textContent?.trim();
                if (text && text.includes('【第一次模拟') && text.length > 100) {
                    description = text;
                    break;
                }
            }
        }

        // 获取封面图片 - 从 .cover-img 元素的 background-image 样式
        const coverElements = document.querySelectorAll('.cover-img');
        for (const coverElement of coverElements) {
            const style = coverElement.getAttribute('style') || '';
            if (style.includes('background-image')) {
                // 提取 background-image URL
                const match = style.match(/background-image:\s*url\(["']?([^"')]+)["']?\)/);
                if (match) {
                    cover = match[1].trim();
                    break;
                }
            }
        }

        // 如果没找到封面，尝试其他方式
        if (!cover) {
            const imgElement = document.querySelector('img[src*="cover"]') ||
                              document.querySelector('img[src*="book"]') ||
                              document.querySelector('img');
            cover = imgElement?.getAttribute('src') || '';
        }

        // 尝试获取作者信息 - 从页面中查找作者相关内容
        const authorElements = document.querySelectorAll('*');
        for (const element of authorElements) {
            const text = element.textContent?.trim();
            if (text && text.includes('作者') && text.length < 50) {
                // 提取作者名字
                const match = text.match(/作者[:：]\s*(.+)/);
                if (match) {
                    author = match[1].trim();
                    break;
                }
            }
        }

        // 获取章节列表
        const chapterElements = document.querySelectorAll('div[class*="chapter"], div[data-testid*="chapter"], .chapter-item');
        const chapters: any[] = [];

        chapterElements.forEach((element, index) => {
            const linkElement = element.querySelector('a') || element;
            const title = linkElement.textContent?.trim();
            const href = linkElement.getAttribute('href') ||
                         element.getAttribute('data-href') || '';

            if (title && href) {
                chapters.push({
                    title,
                    url: href.startsWith('http') ? href : `https://fanqienovel.com${href}`,
                    index: index + 1,
                });
            }
        });

        // 如果没有找到章节，尝试从页面中查找可能的章节链接
        if (chapters.length === 0) {
            const possibleChapterLinks = document.querySelectorAll('a[href*="chapter"], a[href*="read"]');
            possibleChapterLinks.forEach((element, index) => {
                const title = element.textContent?.trim();
                const href = element.getAttribute('href') || '';
                if (title && href && title.includes('第')) {
                    chapters.push({
                        title,
                        url: href.startsWith('http') ? href : `https://fanqienovel.com${href}`,
                        index: index + 1,
                    });
                }
            });
        }

        return {
            title,
            author,
            cover,
            description,
            category,
            wordCount,
            status,
            chapterList: chapters,
        };
      });

      return novelInfo;
    } finally {
      await page.close();
    }
  }

  async getChapterContent(chapterUrl: string): Promise<ChapterContent> {
    await this.initBrowser();
    const page = await this.browser.newPage();

    try {
      await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
      await page.goto(chapterUrl, { waitUntil: 'networkidle2' });

      const chapterContent = await page.evaluate(() => {
        const title = document.querySelector('h1')?.textContent?.trim() || '';
        const contentElement = document.querySelector('.chapter-content');
        const content = contentElement?.textContent?.trim() || '';

        return {
          title,
          content,
          index: 0, // 由调用方设置
        };
      });

      return chapterContent;
    } finally {
      await page.close();
    }
  }

  /**
   * 解析番茄分享链接，获取真实的小说页面URL
   * @param shareUrl 番茄分享链接
   * @returns 真实的小说页面URL
   */
  async parseShareUrl(shareUrl: string): Promise<string> {
    await this.initBrowser();
    const page = await this.browser.newPage();

    try {
      await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');

      // 监听页面跳转
      let finalUrl = shareUrl;
      page.on('response', (response) => {
        if (response.status() === 302 || response.status() === 301) {
          const location = response.headers()['location'];
          if (location && location.includes('fanqienovel.com')) {
            finalUrl = location.startsWith('http') ? location : `https://fanqienovel.com${location}`;
          }
        }
      });

      await page.goto(shareUrl, {
        waitUntil: 'networkidle2',
        timeout: 30000
      });

      // 等待页面加载完成，检查是否有重定向
      await page.waitForTimeout(3000);

      // 获取当前页面的最终URL
      finalUrl = page.url();

      // 如果当前URL不是fanqienovel.com，尝试从页面中提取链接
      if (!finalUrl.includes('fanqienovel.com')) {
        const extractedUrl = await page.evaluate(() => {
          // 尝试从各种可能的位置提取小说链接
          const selectors = [
            'a[href*="fanqienovel.com"]',
            'a[href*="novel.toutiao.com"]',
            '[data-url]',
            'script'
          ];

          for (const selector of selectors) {
            const elements = document.querySelectorAll(selector);
            for (const element of elements) {
              const url = element.getAttribute('href') || element.getAttribute('data-url');
              if (url && (url.includes('fanqienovel.com') || url.includes('novel.toutiao.com'))) {
                return url.startsWith('http') ? url : `https://fanqienovel.com${url}`;
              }
            }
          }

          // 如果找不到，尝试从脚本中提取
          const scripts = document.querySelectorAll('script');
          for (const script of scripts) {
            const content = script.textContent;
            if (content && content.includes('fanqienovel.com')) {
              const match = content.match(/https:\/\/[^'"\s]*fanqienovel\.com[^'"\s]*/);
              if (match) return match[0];
            }
          }

          return null;
        });

        if (extractedUrl) {
          finalUrl = extractedUrl;
        }
      }

      return finalUrl;
    } finally {
      await page.close();
    }
  }

  async onModuleDestroy() {
    if (this.browser) {
      await this.browser.close();
    }
  }
}